const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server, {
  allowEIO3: true,
  cors: {
    origin: 'http://localhost:8080',
    methods: ['GET', 'POST'],
    credentials: true
  }
})

// 托管静态资源目录
app.use(express.static('../public'))

app.get('/', (req, res) => {
  // // res.sendFile(__dirname + "/index.html");
  // res.redirect('/index.html')
})
// const socketList = []
const list = []
// 连接事件
io.on('connection', (socket) => {
  console.log('连接成功')
  // 用户登录
  socket.on('login', (msg, callback) => {
    console.log(msg)
    var islogin = true
    io.sockets.sockets.forEach((iss) => {
      if (iss.username === msg.username) {
        islogin = false
      }
    })
    if (!islogin) {
      callback(false)
      return
    }
    callback(true)
    socket.emit('login', msg)

    socket.username = msg.username
    socket.avatar = msg.avatar
    list.push(msg)
    io.emit('getUserList', list)
  })
  // 获取在线用户
  socket.on('getUserList', () => {
    socket.emit('getUserList', list)
  })
  // 进入聊天室 进行广播
  socket.on('toChatRoom', () => {
    console.log(`${socket.username}进入聊天室`)
    io.emit('toChatRoom', { message: `"${socket.username}"进入聊天室` })
  })
  // 离开聊天室 进行广播
  socket.on('outChatRoom', () => {
    console.log(`${socket.username}离开聊天室`)
    io.emit('toChatRoom', { message: `"${socket.username}"离开聊天室` })
  })
  // 聊天室发消息 进行广播
  socket.on('send', (message) => {
    io.emit('toChatRoom', { username: socket.username, avatar: socket.avatar, message: message })
  })
  /* 用户掉线 */
  socket.on('disconnect', () => {
    console.log(`${socket.username}用户离开`)
    /* 删除用户 */
    const index = list.findIndex((i) => i.username === socket.username)
    if (index !== -1) {
      list.splice(index, 1)
      /* 通知前端 */
      io.emit('getUserList', list)
    }
  })
})

server.listen(3000, () => {
  console.log('服务启动成功 端口:3000')
})
